package sz.szsmk.citizencard.ui.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.chenenyu.router.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.ServiceNetActivityBinding;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.model.network.bean.response.PrepayResponse;
import sz.szsmk.citizencard.model.network.bean.response.ServiceTypeRes;
import sz.szsmk.citizencard.model.network.bean.response.UserBean;
import sz.szsmk.citizencard.model.network.bean.response.WebsiteTypeRes;
import sz.szsmk.citizencard.model.network.dzbean.res.MessageEvent;
import sz.szsmk.citizencard.mvp.contract.ISerNetworkContact;
import sz.szsmk.citizencard.mvp.presenter.SerNetworkPresenter;

import sz.szsmk.citizencard.ui.adapter.AllTypeAdapter;
import sz.szsmk.citizencard.ui.adapter.PopRvAdapter;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpThirdView;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.PermissionUtil;
import sz.szsmk.citizencard.util.PubUtils;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/7/11 20:44
 * description:服务网点
 */
@Route("nerwork")
public class ServiceNetworkActivity extends IBaseActivity<SerNetworkPresenter, ServiceNetActivityBinding>
        implements ISerNetworkContact.ISerNetworkView, View.OnClickListener , IBaseActivity.RequestPermissionCallBack {

    LinearLayout typeLayout;
    View transLayout;
    private ArrayList<PrepayResponse.WebsiteListInfoBean> websiteListInfo = new ArrayList<>();
    private ArrayList<PrepayResponse.WebsiteListInfoBean> allInfoList = new ArrayList<>();
    private AllTypeAdapter allTypeAdapter;
    private String mLatitude;
    private String mLongitude;


    private LinearLayout layout;
    private PopupWindow popupWindow;
    private int type = 0;
    private PopRvAdapter popRvAdapter;
    private RecyclerView popRv;
    private ArrayList<String> mDistanceList = new ArrayList<>();
    private ArrayList<String> mServiceList = new ArrayList<>();
    private ArrayList<String> mAreaList = new ArrayList<>();
    private EditText serviceEt;
    private boolean isClick = false;

    private int currentPager = 1;
    private WebsiteTypeRes serviceTypeRes;
    private List<ServiceTypeRes.ServiceTypeInfosBean> serviceTypeInfos;
    private List<WebsiteTypeRes.WebsiteTypeInfoListBean> websiteTypeInfoList;

    private String service_type = "0";
    private String site_type = "0";
    private String distance_type = "0";
    private String distanceId;
    private String charge;
    private int lastSelected = -1;

    private boolean isPopupWindowShow;
    private ArrayList<ImageView> arraws;
    protected String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
    };

    @Override
    protected int attachLayoutRes() {
        return R.layout.service_net_activity;
    }

    @Override
    protected void initInjector() {
        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);
    }

    @Override
    protected void initViews() {
        typeLayout = findViewById(R.id.type_layout);
        transLayout= findViewById(R.id.trans_layout);

        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarDarkFont(true, 0f)
                .statusBarColor(R.color.white).init();
        showLoadingDialog();
        mPresenter.queryServiceTypeApp();
        charge = getIntent().getStringExtra("key");
        if (charge != null) {
            if (charge.contains("provinceCard")) {
                dataBinding.serAllserTv.setText("省一卡通");
                site_type = "3";
                currentPager = 1;
//                dataBinding.contentList.startLoadFirst();
                mPresenter.getWebsiteList(site_type, "0", "0", type, mLatitude, mLongitude, currentPager);
            } else if (charge.contains("")) {
                currentPager = 1;
                dataBinding.serAllserTv.setText("云闪充补登");
                site_type = "8";

//                dataBinding.contentList.startLoadFirst();
                mPresenter.getWebsiteList(site_type, "0", "0", type, mLatitude, mLongitude, currentPager);
            }
            dataBinding.serAllserTv.setTextColor(getResources().getColor(R.color.colorAccent));
        }


        arraws = new ArrayList<>();
        arraws.add(dataBinding.iconArrowType);
        arraws.add(dataBinding.iconArrowSer);
        arraws.add(dataBinding.iconArrowDis);

        layout = (LinearLayout) getLayoutInflater().inflate(R.layout.pup_selectlist, null, false);
        popupWindow = new PopupWindow(layout, LinearLayout.LayoutParams.MATCH_PARENT, 600);
        popRv = (RecyclerView) layout.findViewById(R.id.pop_rv);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        popRv.setLayoutManager(manager);
        popRvAdapter = new PopRvAdapter(this, 0);
        popRv.setAdapter(popRvAdapter);
        initData();
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        // 设置PopupWindow是否能响应外部点击事件
        popupWindow.setOutsideTouchable(true);
        // 设置PopupWindow是否能响应点击事件
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
//        backgroundAlpha(0.5f);
//        backgroundAlpha(1f);

        //添加pop窗口关闭事件
        popupWindow.setOnDismissListener(new poponDismissListener());

        serviceEt = (EditText) findViewById(R.id.service_et);
        serviceEt.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    String type = serviceEt.getText().toString();
                    if (TextUtils.isEmpty(type)) {
                        PubUtils.popTipOrWarn(ServiceNetworkActivity.this, "您未输入任何内容");
                    } else {

                        Bundle bundle = new Bundle();
                        bundle.putString("word", type);
                        bundle.putString("door", "net");
                        JumpUtils.jumptoNatvie(ServiceNetworkActivity.this, "netsearch", 0, bundle);
                    }

                    return true;
                }

                return false;
            }
        });
        allTypeAdapter = new AllTypeAdapter(this);

        dataBinding.contentList.setLayoutManager(new LinearLayoutManager(this));
        dataBinding.contentList.setAdapter(allTypeAdapter);
        dataBinding.swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPager = 1;
                mPresenter.getWebsiteList(site_type, service_type, distance_type, type, mLatitude, mLongitude, currentPager);
            }
        });
        dataBinding.swipeRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getWebsiteList(site_type, service_type, distance_type, type, mLatitude, mLongitude, currentPager);
            }
        });

        //权限提示框
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            PermissionUtil.checkPermission(this,Manifest.permission.ACCESS_FINE_LOCATION,getResources().getString(R.string.location_permission));
            initLocation();//这两个貌似是刷新。
            requestLocation();
        }

        //requestPermissions(this, needPermissions, this);
    }


    private int[] location = new int[2];

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                typeLayout.getLocationOnScreen(location);
                if (ev.getY() < location[1] || ev.getY() > location[1] + typeLayout.getHeight()) {
                    isPopupWindowShow = false;
                }
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    public void setDistanceId(String distanceId) {
        this.distanceId = distanceId;

        switch (distanceId) {
            case "全部距离":
                distance_type = "0";
                break;
            case "500米":
                distance_type = "1";
                break;
            case "1000米":
                distance_type = "2";
                break;
            case "2000米":
                distance_type = "3";
                break;
            case "5000米":
                distance_type = "4";
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    private void initData() {
        mDistanceList.add("全部距离");
        mDistanceList.add("500米");
        mDistanceList.add("1000米");
        mDistanceList.add("2000米");
        mDistanceList.add("5000米");
    }

    @Override
    protected void updateViews() {
        dismissLoadingDialog();
    }

    @Override
    protected void onResume() {
        super.onResume();


        mPresenter.queryWebsiteTypeApp();
    }

    @Override
    public void updataError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        dismissLoadingDialog();
    }

    @Override
    public void updataSuccess(UserBean loginResponse) {

    }

    @Override
    public void getAllListSucc(List<PrepayResponse.WebsiteListInfoBean> websiteListInfo) {
        allInfoList.clear();
        allInfoList.addAll(websiteListInfo);
        dataBinding.swipeRefreshLayout.closeHeaderOrFooter();
    }

    @Override
    public void getAllListFail() {
    }

    @Override
    public void getListSuccess(PrepayResponse prepayResponse) {
        dismissLoadingDialog();
    }

    @Override
    public void serviceSearchSucc(List<PrepayResponse.WebsiteListInfoBean> websiteListInfo) {

        if (websiteListInfo != null) {
            allTypeAdapter.setTypeData(websiteListInfo,0);//0的话是刷新，1是增加
            allTypeAdapter.notifyDataSetChanged();
        }
        dataBinding.swipeRefreshLayout.closeHeaderOrFooter();
    }

    @Override
    public void serviceSearchFail(String msg) {
        dataBinding.swipeRefreshLayout.closeHeaderOrFooter();
    }

    @Override
    public void getWebsiteListSucc(List<PrepayResponse.WebsiteListInfoBean> listInfoBeans) {

        if(currentPager==1){
            this.websiteListInfo.clear();
            this.websiteListInfo.addAll(listInfoBeans);
            allTypeAdapter.setTypeData(websiteListInfo,0);//0的话是刷新，1是增加
        }else{
            this.websiteListInfo.addAll(listInfoBeans);
            allTypeAdapter.setTypeData(websiteListInfo,1);//0的话是刷新，1是增加
        }
        boolean hasMore = listInfoBeans.size() == 15;
        if (hasMore) {
            currentPager++;
        }else{
            //完成加载并标记没有更多数据
            dataBinding.swipeRefreshLayout.finishLoadMoreWithNoMoreData();
        }
        dataBinding.swipeRefreshLayout.closeHeaderOrFooter();
    }

    @Override
    public void getWebsiteListFail() {
        dataBinding.swipeRefreshLayout.closeHeaderOrFooter();
    }

    @Override
    public void queryServiceTypeAppFail() {

    }


    @Override
    public void queryWebsiteTypeAppSucc(WebsiteTypeRes serviceTypeRes) {
        websiteTypeInfoList = serviceTypeRes.getWebsiteTypeInfoList();
        if (websiteTypeInfoList != null) {
            mAreaList.clear();
            mAreaList.add("全部网点");
            for (int i = 0; i < websiteTypeInfoList.size(); i++) {
                mAreaList.add(websiteTypeInfoList.get(i).getType_name());
            }
        }
    }

    private void isHidePop(final int position) {
        if (lastSelected == -1) {
            lastSelected = position;
            ViewCompat.animate(arraws.get(position))
                    .rotation(180)
                    .setDuration(100)
                    .start();
            isPopupWindowShow = true;
        } else if (lastSelected == position) {//收起当前箭头
            ViewCompat.animate(arraws.get(position))
                    .rotation(180)
                    .setDuration(100)
                    .start();
            isPopupWindowShow = true;
        } else if (lastSelected != position) {//收起其他箭头
            arraws.get(position).setRotation(180);
            arraws.get(lastSelected).setRotation(0);
            lastSelected = position;
            isPopupWindowShow = true;
        }
    }


    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    @Override
    public void queryWebsiteTypeAppFail() {

    }

    @Override
    public void granted() {
        initLocation();
        requestLocation();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getCode() == MessageEvent.CODE_LOCTION) {
            EventBus.getDefault().unregister(this);

            //出发自动加载
            dataBinding.swipeRefreshLayout.autoRefresh();
        }
    }

    private void initLocation() {
    }

    private void requestLocation() {
    }

    @Override
    public void denied() {
        finish();
    }

    class poponDismissListener implements PopupWindow.OnDismissListener {

        @Override
        public void onDismiss() {
            backgroundAlpha(1f);
            if (lastSelected != -1) {
                arraws.get(lastSelected).setRotation(0);
            }
            transLayout.setVisibility(View.GONE);
        }

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.back) {
            finish();
        } else if (id == R.id.bj_tv) {
            Bundle bundle = new Bundle();
            bundle.putParcelableArrayList("shopList", websiteListInfo);
            bundle.putString(Constant.SITE_TYPE, site_type);
            bundle.putString(Constant.SERVICE_TYPE, service_type);
            JumpUtils.jumptoNatvie(this, "map", 0, bundle);
        } else if (id == R.id.ser_all_distances) {
            if (lastSelected == 2 && isPopupWindowShow) {
                popupWindow.dismiss();
                isPopupWindowShow = false;
            } else {
                isHidePop(2);
                popRvAdapter.setItemViewData(mDistanceList);
                popRvAdapter.notifyDataSetChanged();
                popupWindow.showAsDropDown(v);

                popRvAdapter.popItemOnclick(new PopRvAdapter.PopItemInterface() {
                    @Override
                    public void onClick(View view, int position) {
                        dataBinding.serDistancesTv.setTextColor(getResources().getColor(R.color.color_00AAFF));
                        if (position == 0) {
                            dataBinding.serDistancesTv.setTextColor(getResources().getColor(R.color.color_3d494f));
                        }
                        dataBinding.serDistancesTv.setText(mDistanceList.get(position));
                        String distance = mDistanceList.get(position);
                        setDistanceId(distance);
                        currentPager = 1;
                        mPresenter.getWebsiteList(site_type, service_type, distance_type, 0, mLatitude, mLongitude, currentPager);
                        popupWindow.dismiss();
                        isClick = false;
                    }
                });
            }
        } else if (id == R.id.ser_all_ser) {
            if (lastSelected == 1 && isPopupWindowShow) {
                popupWindow.dismiss();
                isPopupWindowShow = false;
            } else {
                isHidePop(1);
                popRvAdapter.setItemViewData(mServiceList);
                popRvAdapter.notifyDataSetChanged();
                popupWindow.showAsDropDown(v);
                popRvAdapter.popItemOnclick(new PopRvAdapter.PopItemInterface() {
                    @Override
                    public void onClick(View view, int position) {
                        dataBinding.serAllserTv.setText(mServiceList.get(position));
                        dataBinding.serAllserTv.setTextColor(getResources().getColor(R.color.color_00AAFF));
                        if (position != 0) {
                            site_type = serviceTypeInfos.get(position - 1).getType_id() + "";
                        } else {
                            site_type = "0";
                            dataBinding.serAllserTv.setTextColor(getResources().getColor(R.color.color_3d494f));
                        }
//                        int type_id = websiteTypeInfoList.get(position).getType_id();
                        currentPager = 1;
                        mPresenter.getWebsiteList(site_type, service_type, distance_type, 0, mLatitude, mLongitude, currentPager);
                        popupWindow.dismiss();
                    }
                });
            }
        } else if (id == R.id.ser_all_type) {
            if (lastSelected == 1 && isPopupWindowShow) {
                popupWindow.dismiss();
                isPopupWindowShow = false;
            } else {
                isHidePop(0);
                popRvAdapter.setItemViewData(mAreaList);
                popRvAdapter.notifyDataSetChanged();
                popupWindow.showAsDropDown(v);
                popRvAdapter.popItemOnclick(new PopRvAdapter.PopItemInterface() {
                    @Override
                    public void onClick(View view, int position) {
//                            String distance = mDistanceList.get(position);
//                            setDistanceId(distance);
                        dataBinding.serTypeTv.setText(mAreaList.get(position));
                        dataBinding.serTypeTv.setTextColor(getResources().getColor(R.color.color_00AAFF));
                        if (position != 0) {
                            service_type = websiteTypeInfoList.get(position - 1).getType_id() + "";
                        } else {
                            service_type = "0";
                            dataBinding.serTypeTv.setTextColor(getResources().getColor(R.color.color_3d494f));
                        }
//                        int type_id = websiteTypeInfoList.get(position).getType_id();
                        currentPager = 1;

                        mPresenter.getWebsiteList(site_type, service_type, distance_type, 0, mLatitude, mLongitude, currentPager);
                        popupWindow.dismiss();
                    }
                });
            }
        }
    }

    @Override
    public void queryServiceTypeAppSucc(ServiceTypeRes serviceTypeRes) {
//        this.serviceTypeRes = serviceTypeRes;
        serviceTypeInfos = serviceTypeRes.getServiceTypeInfos();
        if (serviceTypeInfos != null) {
            mServiceList.clear();
            mServiceList.add("全部服务");
            for (int i = 0; i < serviceTypeInfos.size(); i++) {
                mServiceList.add(serviceTypeInfos.get(i).getType_name());
            }
        }
    }

    private void setPopStatus(ImageView v, View view) {
        if (isClick) {
            isClick = false;
            popupWindow.dismiss();
            v.setImageResource(R.drawable.arrow_up);
        } else {
            isClick = true;
            popupWindow.showAsDropDown(view);
            v.setImageResource(R.drawable.arrow_below);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isClick = false;
//        EventBus.getDefault().unregister(this);
    }
}
